import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_test1/api/http/http.dart';
import 'package:flutter_test1/api/http/http_request.dart';
import 'package:flutter_test1/bean/BaseBean.dart';
import 'package:flutter_test1/constant/Constant.dart';
import 'package:flutter_test1/preference/PreferencesManager.dart';

class LoginPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _LoginPage();
  }
}

class _LoginPage extends State<LoginPage>{

  TextEditingController username_controller = TextEditingController(text: "");
  TextEditingController password_controller = TextEditingController(text: "");
  bool password_off = true;
  GlobalKey login_form_key = new GlobalKey<FormState>();
  bool login_button_enable = false;
  String token = "190e35f7e0c0c35d273";//极光注册ID

  @override
  void initState() {
    super.initState();
    username_controller.text = PreferencesManager.getInstance().getString(Constants.USERNAME);
    password_controller.text = PreferencesManager.getInstance().getString(Constants.PASSWORD);
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      if((login_form_key.currentState as FormState).validate()){
        setState(() {
          login_button_enable = true;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("登录"),
        ),
        body: Form(
          key:login_form_key,
          autovalidate: false,
          onChanged: (){
            if((login_form_key.currentState as FormState).validate()){
              login_button_enable = true;
            }else{
              login_button_enable = false;
            }
            setState(() {
            });
          },
          child: new Center(
              child: Padding(
                padding: EdgeInsets.all(20.0),
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    TextFormField(
                      controller: username_controller,
                      decoration: InputDecoration(hintText: "请输入账号",prefixIcon: Icon(Icons.android,color: Colors.blue)),
                      validator: (v){
                        if(v!.trim().length > 0){
                          return null;
                        }else{
                          return "账号不能为空";
                        }
                      },
                    ),
                    TextFormField(
                      controller: password_controller,
                      obscureText: password_off,
                      decoration: InputDecoration(hintText: "请输入密码",prefixIcon: Icon(Icons.password,color: Colors.blue),
                          suffixIcon: IconButton(icon: Icon(password_off? Icons.visibility_off:Icons.visibility), onPressed: () {
                            setState(() {
                              password_off = !password_off;
                            });
                          })),
                      validator: (v){
                        if(v!.trim().length == 0){
                          return "密码不能为空";
                        }else if(v.trim().length < 6){
                          return "密码不能低于6位";
                        }else{
                          return null;
                        }
                      },
                    ),
                    Padding(padding: EdgeInsets.only(top: 30.0)),
                    RaisedButton(
                      disabledColor: Colors.grey,
                      disabledTextColor: Colors.white,
                      color: Colors.blue,
                      textColor: Colors.white,
                      onPressed:login_button_enable? login:null,
                      child: Text("登录"),
                    ),
                  ],
                ),
              )
          ),
        )
    );
  }

  void login() async {
    EasyLoading.show(status: "登录中");
    PreferencesManager.getInstance().putString(Constants.USERNAME, username_controller.text);
    PreferencesManager.getInstance().putString(Constants.PASSWORD, password_controller.text);
    YYResultModel<BaseBean> result = await SRHttpRequest.getInstance().login(username: username_controller.text.trim(), password: generate_MD5(password_controller.text.trim()), token: token);
    if(result.checkRequestSuccess()){
      PreferencesManager.getInstance().putBoolean(Constants.ISLOGIN, true);
      PreferencesManager.getInstance().putString(Constants.TOKEN, result.data!.data!.object!.token);
      PreferencesManager.getInstance().putString(Constants.SHOPID, result.data!.data!.object!.shopId);
      EasyLoading.dismiss();
      Navigator.popAndPushNamed(context, "MainPage");
    }
  }

  // md5 加密
  String generate_MD5(String data) {
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    // 这里其实就是 digest.toString()
    return hex.encode(digest.bytes);
  }
}